package com.example.cdtutils;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 正则表达式工具类
 */
public class RegexUtils {

    /**
     * 匹配第一个字符串
     *
     * @param text
     * @param regex
     * @return
     */
    public static String getMatchString(String text, String regex) {
        String result = "";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(text);
        if (matcher.find()) {
            result = matcher.group();
        }
        return result;
    }

    /**
     * 捕获组
     *
     * @param text
     * @param regex
     * @param group
     * @return
     */
    public static String getMatchGroupString(String text, String regex, int group) {
        String result = "";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(text);
        if (matcher.find()) {
            result = matcher.group(group);
        }
        return result;
    }

    /**
     * 匹配所有结果
     *
     * @param text
     * @param regex
     * @return
     */
    public static List<String> getMatchStrings(String text, String regex) {
        List<String> results = new ArrayList<>();
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(text);
        while (matcher.find()) {
            results.add(matcher.group());
        }
        return results;
    }

    /**
     * 捕获所有分组结果,包含第0组
     * 应用场景：需要的信息分别包含在各个分组内
     * @param text
     * @param regex
     * @param totalGroup 分组数量，即正则中小括号的对数
     * @return
     */
    public static List<String> getMatchGroups(String text, String regex,int totalGroup) {
        List<String> results = new ArrayList<>();
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(text);
        matcher.find();
        for (int i=0;i<=totalGroup;i++) {
            results.add(matcher.group(i));
        }
        return results;
    }
}
